using Infrastructure.Attribute;
using Infrastructure.Extensions;
using JTZY.Model.Goods.Dto;
using JTZY.Model.Goods;
using JTZY.Repository;
using JTZY.Service.Goods.IGoodsService;
using System.Runtime.Versioning;
using static System.Net.Mime.MediaTypeNames;
using JTZY.Model.Brand;
using System.Data;
using Aliyun.OSS;

namespace JTZY.Service.Goods
{
    /// <summary>
    /// 良品Service业务层处理
    /// </summary>
    [AppService(ServiceType = typeof(ICorecmsusergoodsService), ServiceLifetime = LifeTime.Transient)]
    public class CorecmsusergoodsService : BaseService<Corecmsusergoods>, ICorecmsusergoodsService
    {
        /// <summary>
        /// 查询良品列表
        /// </summary>
        /// <param name="parm"></param>
        /// <returns></returns>
        public PagedInfo<CorecmsusergoodsDto> GetList(CorecmsusergoodsQueryDto parm)
        {
            var predicate = QueryExp(parm);

            var response = Queryable()
                //.Includes(x => x.CorecmsuserstockNav) //填充子对象
                .Where(predicate.ToExpression())
                .ToPage<Corecmsusergoods, CorecmsusergoodsDto>(parm);

            return response;
        }

        public PagedInfo<usersgoodsDto> GetGoodsList(CorecmsusergoodsQueryDto parm)
        {
            //var predicate = QueryExp(parm);

            var response = Context.Queryable<Corecmsuserstock>().Where(us => us.UserId == parm.UserId).GroupBy(us => us.GoodId)
                .Select(us => new
                {
                    us.GoodId,
                    prodCount = SqlFunc.AggregateSum<int>(us.Marketable == 1 ? 0 : 1),
                    Stock = SqlFunc.AggregateSumNoNull<int>(us.Stock ?? 0),
                    sqlQty = SqlFunc.AggregateSum<int>(us.SaleQty ?? 0),

                })
                .LeftJoin<Corecmsusergoods>((us, ug) => us.GoodId == ug.GoodId && ug.UserId == parm.UserId)
                .LeftJoin<Corecmsgoods>((us, ug, g) => ug.GoodId == g.Id)
                .LeftJoin<Corecmsbrand>((us, ug, g, b) => ug.GoodBrand == b.Id)
                .WhereIF(!string.IsNullOrEmpty(parm.Bn), (us, ug, g, b) => (g.Bn == parm.Bn || g.Name == parm.Bn))
                .WhereIF(parm.IsMarketable.HasValue, (us, ug, g, b) => ug.Marketable == parm.IsMarketable)

                //.LeftJoin<Corecmsuserstock>((ug, g,us)=>ug.GoodId==us.GoodId&&ug.UserId==us.UserId)
                .Select((us, ug, g, b) => new usersgoodsDto
                {
                    goodId = ug.GoodId,
                    name = ug.GoodName ?? g.Name,
                    prodCount = us.prodCount,
                    image = g.Image,
                    bn = g.Bn,
                    brandName = b.Name,
                    goodsCategoryId = g.GoodsCategoryId,
                    stock = us.Stock,
                    saleQty = us.sqlQty,
                    marketable = ug.Marketable.ToString(),
                }).ToPage<usersgoodsDto>(parm);
            return response;


        }

        /// <summary>
        /// 获取详情
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public Corecmsusergoods GetInfo(long Id)
        {
            var response = Queryable()
                .Includes(x => x.CorecmsuserstockNav) //填充子对象
                .Where(x => x.Id == Id)
                .First();

            return response;
        }

        /// <summary>
        ///  
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="goodId"></param>
        /// <returns></returns>
        public Corecmsusergoods GetInfo(long userId, int goodId)
        {
            var response = Queryable()
                 .Where(x => x.GoodId == goodId && x.UserId == userId)
                 .First();

            return response;
        }

        /// <summary>
        /// 添加良品
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public Corecmsusergoods AddCorecmsusergoods(Corecmsusergoods model)
        {
            return Context.InsertNav(model).Include(s1 => s1.CorecmsuserstockNav).ExecuteReturnEntity();
        }

        /// <summary>
        /// 修改良品
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public int UpdateCorecmsusergoods(Corecmsusergoods model)
        {
            var res = UseTran(() =>
            {
                int upres = Context.Updateable<Corecmsusergoods>(model).ExecuteCommand();
                if (upres > 0)
                    model.CorecmsuserstockNav.ForEach(t =>
                    {
                        if ((t.Vip0 > 0 && t.Vip0 < t.ProductCostPrice)
                        || (t.Vip1 > 0 && t.Vip1 < t.ProductCostPrice)
                        || (t.Vip2 > 0 && t.Vip2 < t.ProductCostPrice)
                        || (t.Vip3 > 0 && t.Vip3 < t.ProductCostPrice)
                        || (t.Vip4 > 0 && t.Vip4 < t.ProductCostPrice))
                        {
                            throw new Exception("价格设置错误");
                        }
                        if (t.Vip0 > 0)
                            t.InvalVip0 = t.Vip0 - t.ProductCostPrice;
                        if (t.Vip1 > 0)
                            t.InvalVip1 = t.Vip1 - t.ProductCostPrice;
                        if (t.Vip2 > 0)
                            t.InvalVip2 = t.Vip2 - t.ProductCostPrice;
                        if (t.Vip3 > 0)
                            t.InvalVip3 = t.Vip3 - t.ProductCostPrice;
                        if (t.Vip4 > 0)
                            t.InvalVip4 = t.Vip4 - t.ProductCostPrice;

                    });

                Context.Updateable<Corecmsuserstock>(model.CorecmsuserstockNav).UpdateColumns(it =>
                        new
                        {
                            it.InvalVip0,
                            it.InvalVip1,
                            it.InvalVip2,
                            it.InvalVip3,
                            it.InvalVip4,
                            it.Vip0,
                            it.Vip1,
                            it.Vip2,
                            it.Vip3,
                            it.Vip4,
                            it.SkuImage,
                            it.SkuName
                        })
                        .ExecuteCommand();
            });

            return res.IsSuccess ? 1 : 0;// Context.UpdateNav(model).Include(z1 => z1.CorecmsuserstockNav).ExecuteCommand() ? 1 : 0;
        }

        public WebApiCallBack Marketable(Corecmsusergoods modal)
        {
            var jm = new WebApiCallBack();
            //int updateNums = 0;
            var res = UseTran(() =>
            {
                var list = Context.Queryable<Corecmsuserstock>().Where(it => it.GoodId == modal.GoodId && it.UserId == modal.UserId).ToList();
                foreach (var item in list)
                {
                    if (!item.InvalVip0.HasValue || !item.InvalVip1.HasValue || !item.InvalVip2.HasValue || !item.InvalVip3.HasValue || !item.InvalVip4.HasValue)
                    {
                        throw new Exception("请先设置会员等级价格");
                    }
                    item.Marketable = modal.Marketable;
                    if (modal.Marketable == 1)
                    {
                        item.Vip0 = item.ProductCostPrice + item.InvalVip0.Value;
                        item.Vip1 = item.ProductCostPrice + item.InvalVip1.Value;
                        item.Vip2 = item.ProductCostPrice + item.InvalVip2.Value;
                        item.Vip3 = item.ProductCostPrice + item.InvalVip3.Value;
                        item.Vip4 = item.ProductCostPrice + item.InvalVip4.Value;
                        item.SaleStock = item.Stock ?? 0;
                    }
                }
                Context.Updateable<Corecmsuserstock>(list).WhereColumns(us => us.Id).UpdateColumns(us => new { us.Vip0, us.Vip1, us.Vip2, us.Vip3, us.Vip4, us.SaleStock, us.Marketable }).ExecuteCommand();
                Update(u => u.GoodId == modal.GoodId && u.UserId == modal.UserId, it => new Corecmsusergoods() { Marketable = modal.Marketable, UpdateTime = DateTime.Now });
            });
            jm.msg = res.ErrorMessage;
            jm.status = res.IsSuccess;
            return jm;
        }

        /// <summary>
        /// 查询导出表达式
        /// </summary>
        /// <param name="parm"></param>
        /// <returns></returns>
        private static Expressionable<Corecmsusergoods> QueryExp(CorecmsusergoodsQueryDto parm)
        {
            var predicate = Expressionable.Create<Corecmsusergoods>();
            //predicate= predicate.AndIF(parm.Marketable.HasValue,);
            return predicate;
        }

        public PagedInfo<usersgoodsDto> ExportList(CorecmsusergoodsQueryDto parm)
        {
            //var predicate = QueryExp(parm);

            var response = Context.Queryable<Corecmsuserstock>().Where(us => us.UserId == parm.UserId).GroupBy(us => us.GoodId)
                .Select(us => new
                {
                    us.GoodId,
                    prodCount = SqlFunc.AggregateSum<int>(us.Marketable == 1 ? 0 : 1),
                    Stock = SqlFunc.AggregateSumNoNull<int>(us.Stock ?? 0),
                    sqlQty = SqlFunc.AggregateSum<int>(us.SaleQty ?? 0),

                })
                .LeftJoin<Corecmsusergoods>((us, ug) => us.GoodId == ug.GoodId && ug.UserId == parm.UserId)
                .LeftJoin<Corecmsgoods>((us, ug, g) => ug.GoodId == g.Id)
                .LeftJoin<Corecmsbrand>((us, ug, g, b) => ug.GoodBrand == b.Id)
                .WhereIF(!string.IsNullOrEmpty(parm.Bn), (us, ug, g, b) => (g.Bn == parm.Bn || g.Name == parm.Bn))
                .WhereIF(parm.IsMarketable.HasValue, (us, ug, g, b) => ug.Marketable == parm.IsMarketable)

                //.LeftJoin<Corecmsuserstock>((ug, g,us)=>ug.GoodId==us.GoodId&&ug.UserId==us.UserId)
                .Select((us, ug, g, b) => new usersgoodsDto
                {
                    goodId = ug.GoodId,
                    name = ug.GoodName ?? g.Name,
                    prodCount = us.prodCount,
                    image = g.Image,
                    bn = g.Bn,
                    brandName = b.Name,
                    goodsCategoryId = g.GoodsCategoryId,
                    catetoryName = g.categoryArr,
                    stock = us.Stock,
                    saleQty = us.sqlQty,
                    marketable = ug.Marketable.ToString() == "1" ? "上架" : "未上架",
                }).ToPage<usersgoodsDto>(parm);

            //处理类别
            var categoryIds = response.Result.Select(e => e.catetoryName).ToList();

            if (categoryIds.Count() > 0)
            {
                var categoryArr = new List<string>();
                categoryIds.ForEach(e => categoryArr.AddRange(e.Split(',')));

                var categoryList = Context.Queryable<Corecmsgoodscategory>().Where(e => categoryArr.Contains(e.Id.ToString())).ToList();
                foreach (var dto in response.Result)
                {
                    var categoryArrOne = dto.catetoryName.Split(',');
                    dto.catetoryName = "";
                    for (var i = 0; i < categoryArrOne.Length; i++)
                    {
                        var firstCategory = categoryList.FirstOrDefault(e => e.Id.ToString() == categoryArr[i]);
                        if (firstCategory != null)
                        {
                            dto.catetoryName += firstCategory.Name + "/";
                        }
                    }
                    if (!string.IsNullOrEmpty(dto.catetoryName))
                        dto.catetoryName = dto.catetoryName.TrimEnd('/');
                }
            }
            return response;


        }
    }
}